package service

import (
	"errors"
	"gorm.io/gorm"
	"strings"
	"vrcm/src/vrcm/app/admin/models/subject"
	"vrcm/src/vrcm/common/service"

	"vrcm/src/vrcm/app/admin/service/dto/subject"
	"vrcm/src/vrcm/common/actions"
	cDto "vrcm/src/vrcm/common/dto"
)

type AnswerRecord struct {
	service.Service
}

// GetPage 获取AnswerRecord列表
func (e *AnswerRecord) GetPage(c *dto.AnswerRecordGetPageReq, p *actions.DataPermission, list *[]subject.AnswerRecord, count *int64) error {
	var err error
	var data subject.AnswerRecord

	err = e.Orm.Model(&data).
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
			actions.Permission(data.TableName(), p),
		).
		Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("AnswerRecordService GetPage error:%s \r\n", err)
		return err
	}
	return nil
}

// Get 获取AnswerRecord对象
func (e *AnswerRecord) Get(d *dto.AnswerRecordGetReq, p *actions.DataPermission, model *subject.AnswerRecord) error {
	var data subject.AnswerRecord

	err := e.Orm.Model(&data).
		Scopes(
			actions.Permission(data.TableName(), p),
		).
		First(model, d.GetId()).Error
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		err = errors.New("查看对象不存在或无权查看")
		e.Log.Errorf("Service GetAnswerRecord error:%s \r\n", err)
		return err
	}
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return err
	}
	return nil
}

// GetByAccount Get 获取AnswerRecord对象
func (e *AnswerRecord) GetByAccount(d *dto.AnswerRecordGetReq) (*subject.AnswerRecord, error) {
	var data subject.AnswerRecord
	err := e.Orm.Model(&data).Where(&subject.AnswerRecord{TenantId: d.TenantId, EventId: d.EventId, SubjectId: d.SubjectId, IsDelete: 2, Type: 1}).First(&data).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		err = errors.New("查看对象不存在或无权查看")
		e.Log.Errorf("Service GetAnswerRecord error:%s \r\n", err)
		return nil, err
	}
	if data.Id <= 0 {
		return nil, nil
	}
	return &data, nil
}

// Insert 创建AnswerRecord对象
func (e *AnswerRecord) Insert(c *dto.AnswerRecordInsertReq) error {
	var err error
	var data subject.AnswerRecord
	//tx := e.Orm.Begin()
	//defer func() {
	//	if r := recover(); r != nil {
	//		tx.Rollback()
	//	}
	//}()
	//if err := tx.Error; err != nil {
	//	return err
	//}
	//判断是否回答过该题目
	//if c.Type == 1 {
	//	err = e.Orm.Model(&subject.AnswerRecord{}).Where(&subject.AnswerRecord{TenantId: c.TenantId, SubjectId: c.SubjectId, PaperId: c.PaperId, EventId: c.EventId, Account: c.Account, IsDelete: 2}).First(&data).Error
	//
	//	if data.Id > 0 {
	//		return errors.New("已经答过该题,不能重复作答")
	//	}
	//
	//	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
	//		tx.Rollback()
	//		return err
	//	}
	//}

	c.Generate(&data)
	//获取正确答案
	data, err = e.ProcessAnswer(data)
	if err != nil {
		e.Log.Errorf("subject select error:%s \r\n", err)
		return err
	}
	err = e.Orm.Create(&data).Error

	if err != nil && strings.Contains(err.Error(), "Error 1062: Duplicate entry") {
		return errors.New("已经答过该题,不能重复作答")
	}
	if err != nil {
		e.Log.Errorf("AnswerRecordService Insert error:%s \r\n", err)
		return err
	}
	c.Id = data.Id
	return nil
}

// Update 修改AnswerRecord对象
func (e *AnswerRecord) Update(c *dto.AnswerRecordUpdateReq, p *actions.DataPermission) error {
	var err error
	var data = subject.AnswerRecord{}
	e.Orm.First(&data, c.GetId())
	c.Generate(&data)

	db := e.Orm.Save(&data)
	if err = db.Error; err != nil {
		e.Log.Errorf("AnswerRecordService Save error:%s \r\n", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权更新该数据")
	}
	return nil
}

// Remove 删除AnswerRecord
func (e *AnswerRecord) Remove(d *dto.AnswerRecordDeleteReq, p *actions.DataPermission) error {
	var data subject.AnswerRecord

	db := e.Orm.Model(&data).
		Scopes(
			actions.Permission(data.TableName(), p),
		).Delete(&data, d.GetId())
	if err := db.Error; err != nil {
		e.Log.Errorf("Service RemoveAnswerRecord error:%s \r\n", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权删除该数据")
	}
	return nil
}

// ProcessAnswer 判断答案是否正确
func (e *AnswerRecord) ProcessAnswer(data subject.AnswerRecord) (subject.AnswerRecord, error) {
	//获取正确答案
	s := &subject.Subject{}
	err := e.Orm.Where(map[string]interface{}{"id": data.SubjectId, "paper_id": data.PaperId, "is_delete": 2}).First(s).Error
	if err != nil {
		e.Log.Errorf("subject select error:%s \r\n", err)
		return data, errors.New("没有找到题目")
	}
	if s.Answer == data.Answer {
		data.IsRight = 1
	} else if len(data.Answer) <= 0 {
		data.IsRight = 3
	} else {
		data.IsRight = 2
	}
	return data, nil
}

// IsAnswered 判断题目是否被回答过
func (e *AnswerRecord) IsAnswered(c *dto.AnswerRecordInsertReq) error {
	var data subject.AnswerRecord
	//判断是否回答过该题目
	e.Orm.Where(&subject.AnswerRecord{TenantId: c.TenantId, SubjectId: c.SubjectId, EventId: c.EventId, PaperId: c.PaperId, Account: c.Account, IsDelete: 2}).First(&data)
	if data.Id > 0 {
		return errors.New("已经答过该题,不能重复作答")
	}
	return nil
}
